﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using System.Security.Principal;
using kxcxw.Data.Common;
using System.ComponentModel.DataAnnotations;
using System.Collections;

namespace KXCXW.Web
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public MvcApplication()
        {
            AuthorizeRequest += new EventHandler(MvcApplication_AuthorizeRequest);
        }

        void MvcApplication_AuthorizeRequest(object sender, EventArgs e)
        {
            IIdentity id = Context.User.Identity;
            if (id.IsAuthenticated)
            {
                string[] roles = (new AccountRepositories()).GetRoles(id.Name);
                if (roles[0] != DataConstants.Member)
                    Context.User = new GenericPrincipal(id, roles);
            }
        }
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("{resource}.html/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );
            //routes.MapRoute(
            //    "Route_2", // Route name
            //    "{controller}/{action}/{categoryId}", // URL with parameters
            //    new { controller = "Home", action = "ProductList", categoryId = UrlParameter.Optional} // Parameter defaults
            //);
            //routes.MapRoute(
            //    "Route_3", // Route name
            //    "{controller}/{action}/{categoryId}/{typeId}", // URL with parameters
            //    new { controller = "Home", action = "ProductList", categoryId = UrlParameter.Optional, typeId = UrlParameter.Optional } // Parameter defaults
            //);
            //routes.MapRoute(
            //    "Route_4", // Route name
            //    "{controller}/{action}/{PromotionType}/{PromotionTypeId}/{typeId}", // URL with parameters
            //    new { controller = "Home", action = "MoreList", PromotionType = UrlParameter.Optional, PromotionTypeId = UrlParameter.Optional, typeId = UrlParameter.Optional } // Parameter defaults
            //);
        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            ViewEngines.Engines.Add(new AdminViewEngine());

            DataAnnotationsModelValidatorProvider.RegisterAdapterFactory(typeof(RequiredAttribute),
                (m, c, a) => new MyRequiredAttributeAdApter(m, c, (RequiredAttribute)a));
        }

        void Application_BeginRequest(object sender, EventArgs e)
        {
            /* Fix for the Flash Player Cookie bug in Non-IE browsers.
            * Since Flash Player always sends the IE cookies even in FireFox
            * we have to bypass the cookies by sending the values as part of the POST or GET
            * and overwrite the cookies with the passed in values.
            *
            * The theory is that at this point (BeginRequest) the cookies have not been ready by
            * the Session and Authentication logic and if we update the cookies here we'll get our
            * Session and Authentication restored correctly
            */

            try
            {
                string session_param_name = "ASPSESSID";
                string session_cookie_name = "ASP.NET_SESSIONID";

                if (HttpContext.Current.Request.Form[session_param_name] != null)
                {
                    UpdateCookie(session_cookie_name, HttpContext.Current.Request.Form[session_param_name]);
                }
                else if (HttpContext.Current.Request.QueryString[session_param_name] != null)
                {
                    UpdateCookie(session_cookie_name, HttpContext.Current.Request.QueryString[session_param_name]);
                }
            }
            catch (Exception)
            {
            }

            try
            {
                string auth_param_name = "AUTHID";
                string auth_cookie_name = FormsAuthentication.FormsCookieName;

                if (HttpContext.Current.Request.Form[auth_param_name] != null)
                {
                    UpdateCookie(auth_cookie_name, HttpContext.Current.Request.Form[auth_param_name]);
                }
                else if (HttpContext.Current.Request.QueryString[auth_param_name] != null)
                {
                    UpdateCookie(auth_cookie_name, HttpContext.Current.Request.QueryString[auth_param_name]);
                }

            }
            catch (Exception)
            {
            }
        }
        void UpdateCookie(string cookie_name, string cookie_value)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookie_name);
            if (cookie == null)
            {
                HttpCookie cookie1 = new HttpCookie(cookie_name, cookie_value);
                Response.Cookies.Add(cookie1);
            }
            else
            {
                cookie.Value = cookie_value;
                HttpContext.Current.Request.Cookies.Set(cookie);
            }
        }


    }
    public class AdminViewEngine : RazorViewEngine
    {
        private static string[] NewPartialViewFormats = new[] {  
        "~/Areas/Admin/Views/Shared/{0}.cshtml",  
    };

        public AdminViewEngine()
        {
            base.PartialViewLocationFormats = base.PartialViewLocationFormats.Union(NewPartialViewFormats).ToArray();
        }
    }
    public class MyRequiredAttributeAdApter : System.Web.Mvc.RequiredAttributeAdapter
    {
        public MyRequiredAttributeAdApter(ModelMetadata metadata, ControllerContext context,
            RequiredAttribute attribute)
            : base(metadata, context, attribute) { }
        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
        {
            string errorMessage = "";
            if (Attribute.ErrorMessage == "")
                errorMessage = string.Format("{0} 是必须的", Metadata.DisplayName);
            else
                errorMessage = Attribute.ErrorMessage;
            return new[] { new ModelClientValidationRequiredRule(errorMessage) };
        }
    }
}